﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.IO;


namespace LiveProjectManager.Controllers
{
    public class FileController : Controller
    {
        private static DDD.Services.FileService _service = new DDD.Services.FileService();
        protected static DDD.Services.ConfigService _config = new DDD.Services.ConfigService();


        //
        // GET: /File/
        public ActionResult Index(int paginateBy = 0, int page = 1)
        {
            return Json(
                DDD.Services.FileService.toDict(_service.getAll(paginateBy, page)),
                JsonRequestBehavior.AllowGet
            );
        }


        //
        // GET: /File/Details/{Id}
        public ActionResult Details(long id)
        {
            DDD.Domains.File myFile = _service.getById(id);

            // Can't find a matching resource.
            if (myFile == null)
                return new HttpStatusCodeResult((int)HttpStatusCode.NotFound);

            // Return formatted resource.
            return Json(myFile.toDict(), JsonRequestBehavior.AllowGet);
        }


        //
        // POST: /File/Create
        [HttpPost]
        public ActionResult Create(string qqfile)
        {
            string path = Path.Combine(
                    Server.MapPath("~/Content"),
                    (string)_config.getByKey("RESOURCE_UPLOAD_PATH").Value
                );
            var file = string.Empty;
            var fileName = string.Empty;

            try
            {
                var stream = Request.InputStream;
                if (String.IsNullOrEmpty(Request["qqfile"]))
                {
                    // IE
                    HttpPostedFileBase postedFile = Request.Files[0];
                    stream = postedFile.InputStream;
                    file = Path.Combine(path, System.IO.Path.GetFileName(Request.Files[0].FileName));
                    fileName = System.IO.Path.GetFileName(Request.Files[0].FileName);
                }
                else
                {
                    //Webkit, Mozilla
                    file = Path.Combine(path, qqfile);
                    fileName = qqfile;
                }

                var buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                System.IO.File.WriteAllBytes(file, buffer);
                if (!_service.create("/Content/uploads/"+ fileName, buffer.Length))
                    return Json(new { success = false, message = "INTERNAL SERVER ERROR" }, "application/json");
                return Json(new { success = true, file = _service.getByPath("/Content/uploads/" + fileName) }, "text/html");
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message }, "application/json");
            }
        }


        //
        // DELETE: /File/Delete
        [HttpDelete]
        public ActionResult Delete(FormCollection myFormCollection)
        {
            try
            {
                // Entity to delete is not found.
                if (!_service.exists(long.Parse(myFormCollection["Id"])))
                    return new HttpStatusCodeResult((int)HttpStatusCode.NotFound);

                // Unknown error occured, unable to delete.
                if (!_service.remove(long.Parse(myFormCollection["Id"])))
                    return new HttpStatusCodeResult((int)HttpStatusCode.InternalServerError);

                // Deletion successful
                return new HttpStatusCodeResult((int)HttpStatusCode.NoContent);
            }
            catch (Exception)
            {
                return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest, "Invalid Id parameter (must be a long).");
            }
        }
    }
}
